<?php
/**
 * Created by PhpStorm.
 * User: andrei
 * Date: Jun 27, 2012
 * Time: 4:36:21 PM
 * To change this template use File | Settings | File Templates.
 */
 
class Db_Products_Photos extends Common {
	protected static $tableName = TAB_PHOTOS;
	protected static $dbFields = array(
        'id',
		'ph_gallery_id',
		'ph_original',
		'ph_name',
		'ph_path',
		'ph_ow',
		'ph_oh',
		'ph_resized',
		'ph_rw',
		'ph_rh',
		'ph_name_hq',
        'deleted'
	);

	/**
	 * @var Db_Products_Photos
	 */
	public $objectArray;

	public $id;
	public $ph_gallery_id;
	public $ph_original;
	public $ph_name;
	public $ph_path;
	public $ph_ow;
	public $ph_oh;
	public $ph_resized;
	public $ph_rw;
	public $ph_rh;
	public $ph_name_hq;
    public $deleted;

    function __construct($value=NULL, $fieldName=NULL) {
        parent::__construct($value, $fieldName);
    }

	/**
	 * @static
	 * @param array $liIds
	 * @return bool
	 */
	public static function deleteByLiIds($liIds = array()) {
		$liIdsList = implode(',', $liIds);
		self::$DB->q("UPDATE ?f SET `deleted` = 1 WHERE `ph_gallery_id` IN( ? )", self::$tableName, $liIdsList);

		return (self::$DB->mysqlModifiedRows() > 0 ? true : false);
	}

	public static function getPhotosOfProductsByCategoryId($categoryId) {

		if (!$categoryId) {
			return false;
		}
		$sql = "SELECT ph.*, pd.p_name FROM ?f ph
				INNER JOIN ?f pg ON ph.ph_gallery_id = pg.id AND pg.pg_gallery_type = ?
				INNER JOIN ?f pd ON pg.pg_owner_id = pd.id
				INNER JOIN ?f prc ON prc.prc_product_id = pd.id
				WHERE ph.deleted = 0 AND pd.deleted = 0 AND pg.deleted = 0 AND prc.prc_category_id = ?
				GROUP BY ph.id
		";

		$photosProductCategory = self::$DB->q(true, $sql, self::$tableName, TAB_PHOTO_GALLERIES, 'product', TAB_PRODUCTS, TAB_PRODUCT_CATEGORIES, $categoryId);
		$dataReturn  = array();
		$env = conf('ENVIRONMENT');
		while ($data = $photosProductCategory->fetch_object()) {
			$fileName = PUBLIC_RESOURCES_PATH . $data->ph_path . $data->ph_resized;
			if(file_exists($fileName)) {
				$data->ph_original = $data->ph_original . ' (' . ct(T_PRODUCTS_TITLE, $data->p_name) . ')';
				$data->ph_resized = self::$PROJECT['pr_resources_'. $env].$data->ph_path.DS.$data->ph_resized;
				$dataReturn[] = $data;
			}
		}
		return $dataReturn;
	}
}